package org.ws.edu.task2;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.ws.edu.task2.exceptions.ExtensionLengthException;
import org.ws.edu.task2.exceptions.IncorrectSymbolsException;
import org.ws.edu.task2.exceptions.NameLengthException;

public class Validator {
    private static final String REGEX_LAST_ELEMENT_NAME = "(.*)\\..*";
    private static final String REGEX_EXTENSIONS = "\\.(.*)";
    private static final String REGEX_CORRECT_NAME = ".*[^a-zA-Z0-9].*";

    /**
     * 
     * @param s - name of Element
     * @throws ExtensionLengthException
     * @throws NameLengthException
     * @throws IncorrectSymbolsException
     */
    public static void checkElementsNames(String[] s) throws ExtensionLengthException, NameLengthException, IncorrectSymbolsException {
        checkLastElement(s[s.length - 1]);
        for (int i = 1; i < s.length - 1; i++) {
            checkCorrectNameSymbols(s[i]);
            checkElementNameLength(s[i]);
        }
    }

    /**
     * 
     * @param s - name of Element
     * @throws ExtensionLengthException
     */
    private static void checkFileExtensionLength(String s) throws ExtensionLengthException {
        if (s.length() > 3) {
            throw new ExtensionLengthException();
        }
    }

    /**
     * 
     * @param s - name of Element
     * @throws NameLengthException
     */
    private static void checkElementNameLength(String s) throws NameLengthException {
        if (s.length() > 8) {
            throw new NameLengthException();
        }
    }

    /**
     * 
     * @param s - name of Element
     * @throws IncorrectSymbolsException
     */
    private static void checkCorrectNameSymbols(String s) throws IncorrectSymbolsException {

        Pattern pattern = Pattern.compile(REGEX_CORRECT_NAME);
        Matcher matcher = pattern.matcher(s);
        if (matcher.matches()) {
            throw new IncorrectSymbolsException();
        }
    }

    /**
     * 
     * @param s - name of Element
     * @throws ExtensionLengthException
     * @throws NameLengthException
     * @throws IncorrectSymbolsException
     */
    private static void checkLastElement(String s) throws ExtensionLengthException, NameLengthException, IncorrectSymbolsException {
        Pattern pattern = Pattern.compile(REGEX_EXTENSIONS);
        Matcher matcher = pattern.matcher(s);
        if (matcher.find()) {
            checkFileExtensionLength(matcher.group(1));
            pattern = Pattern.compile(REGEX_LAST_ELEMENT_NAME);
            if (matcher.find()) {
                checkCorrectNameSymbols(matcher.group(1));
                checkElementNameLength(matcher.group(1));
            }
        } else {
            checkCorrectNameSymbols(s);
            checkElementNameLength(s);
        }
    }

}
